package com.zly.lab.blog.controller;

import com.github.pagehelper.PageInfo;
import com.zly.lab.blog.entity.Article;
import com.zly.lab.blog.entity.Statistic;
import com.zly.lab.blog.service.ArticleService;
import com.zly.lab.blog.service.StatisticService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

@Slf4j
@Controller
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private StatisticService statisticService;

    @GetMapping("/page/{pageNum}")
    public String articlePage(@PathVariable("pageNum") Integer pageNum,@RequestParam(defaultValue = "5") Integer pageSize ,HttpServletRequest request) {
        PageInfo<Article> articlePage = articleService.getArticlePage(pageNum, pageSize);
        request.setAttribute("articles", articlePage);
        ArrayList<Article> articles = new ArrayList<>();
        for (Statistic heatDatum : statisticService.getHeatData()) {
            Article articleById = articleService.getArticleById(heatDatum.getArticleId());
            Integer hits = heatDatum.getHits();
            Integer commentsNum = heatDatum.getCommentsNum();
            articleById.setHits(hits);
            articleById.setCommentsNum(commentsNum);
            articles.add(articleById);
        }
        request.setAttribute("articleList",articles);
        return "client/index";
    }

    @RequestMapping(value = {"", "/", "/index"})
    public String index(HttpServletRequest request) {
        //获取文章数据
        articlePage(1,5,request);
        return "client/index";
    }
}
